var category = "";
var eventData;
var doctor;
var starts;
var ends;
var tiem = new Date();
var YY = tiem.getFullYear();
var MM = tiem.getMonth() + 1;
var DD = tiem.getDate();
if (MM < 10) {
    MM = "0" + MM
}
if (DD < 10) {
    DD = "0" + DD
}
var hour = tiem.getHours();
var minute = tiem.getMinutes();
if (hour < 10) {
    hour = "0" + hour
}
if (minute < 10) {
    minute = "0" + minute
}
starts = YY + "-" + MM + "-" + DD + " 00:00:00";
ends = YY + "-" + MM + "-" + DD + " 23:59:59";

function continued(obj) {
    var time = $("#duration").val();
    if (obj == "-") {
        if (time == 0) {
            $("#duration").val(0);
            viewUpdate()
        } else {
            $("#duration").val(parseInt(time) - 15);
            viewUpdate()
        }
    } else if (obj == "+") {
        $("#duration").val(parseInt(time) + 15);
        viewUpdate()
    }
}

function viewUpdate() {
    var start = $("#startTime").val();
    var date = new Date(start.replace("-", "/"));
    date.setMinutes(date.getMinutes() + parseInt($("#duration").val()), date.getSeconds(), 0);
    var ends = new Date(date);
    var currentYear = ends.getFullYear();
    var currentMonth = ends.getMonth() + 1;
    var currentDay = ends.getDate();
    var currentHours = ends.getHours();
    var currentMinutes = ends.getMinutes();
    if (currentMonth < 10) currentMonth = "0" + currentMonth;
    if (currentDay < 10) currentDay = "0" + currentDay;
    if (currentHours < 10) currentHours = "0" + currentHours;
    if (currentMinutes < 10) currentMinutes = "0" + currentMinutes;
    var end = currentYear + "-" + currentMonth + '-' + currentDay + ' ' + currentHours + ':' + currentMinutes;
    $('#calendars').fullCalendar('select', start, end, true)
}

$(function () {
    var customerSex2 = document.getElementById('customerSex2').value;
    if (customerSex2 == '1') {
        document.getElementById('customerSex').innerHTML = '男'
    } else if (customerSex2 == '2') {
        document.getElementById('customerSex').innerHTML = '女'
    } else {
        document.getElementById('customerSex').innerHTML = '未知'
    }
    getListInfo()
    $.ajax({
        url: Feng.ctxPath + "/consultant/getDoctor", type: "get", success: function (data) {
            var txt = '<option value="未指定医生">未指定医生</option>';
            for (var i = 0; i < data.length; i++) {
                txt += '<option value="' + data[i].doctor + '">' + data[i].doctor + '</option>'
            }
            document.getElementById('doctor').innerHTML = txt;
            var seleteDoctorValue = $('#doctorValue').val();
            if (seleteDoctorValue != "") {
                $("#doctor option[value=" + seleteDoctorValue + "]").attr("selected", "selected")
            }
        }, error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        }
    });
    $.post(Feng.ctxPath + "/tc/getLists", function (data) {
        var txt = '<option value="待定TC">待定TC</option>';
        for (var i = 0; i < data.length; i++) {
            txt += '<option value="' + data[i].tcName + '">' + data[i].tcName + '</option>'
        }
        document.getElementById('fieldTc').innerHTML = txt;
        var seletetcName = $('#queryTcValue').val();
        if (seletetcName != "") {
            $("#fieldTc option[value=" + seletetcName + "]").attr("selected", "selected")
        }
    }, "json");
    $.post(Feng.ctxPath + "/payService/getDepartment", function (data) {
        var txt = '<option value="待定">待定</option>';
        for (var i = 0; i < data.length; i++) {
            txt += '<option value="' + data[i].department + '">' + data[i].department + '</option>'
        }
        document.getElementById('treatmentUnit').innerHTML = txt;
        var treatmentUnitValue = $("#treatmentUnitValue").val();
        if (treatmentUnitValue != "") {
            $("#treatmentUnit option[value=" + treatmentUnitValue + "]").attr("selected", "selected")
        }
    }, "json");
    $("#startDocumentValue").val(starts);
    $('#calendars').fullCalendar({
        header: {left: '', center: '', right: ''},
        defaultView: 'agendaDay',
        allDaySlot: false,
        selectable: true,
        selectHelper: true,
        editable: false,
        eventLimit: true,
        nowIndicator: true,
        minTime: "08:00:00",
        maxTime: "20:00:00",
        titleFormat: 'YYYY-MM-DD',
        slotDuration: "00:15:00",
        slotLabelFormat: 'HH',
        slotLabelInterval: "00:60:00",
        slotLabelFormats: 'mm',
        slotLabelIntervals: "00:15:00",
        selectMinDistance: 30,
        height: window.innerHeight - 108,
        select: function (startDate, endDate, jsEvent, view, resource) {
            var start = startDate.format('YYYY-MM-DD HH:mm:ss');
            var end = endDate.format('YYYY-MM-DD HH:mm:ss');
            var start1 = new Date(start);
            var end1 = new Date(end);
            var continued = parseInt(end1 - start1) / 1000 / 60;
            $("#startTime").val(start);
            $("#duration").val(continued);
            var docName = document.getElementById("doctorValue").value;
            eventData = start + "," + end + "," + docName
        },
        timeFormat: 'H:mm',
        slotEventOverlap: false,
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        aspectRatio: 0.6,
        events: function (start, end, timezone, callback) {
            start = starts;
            end = ends;
            doctor = document.getElementById('doctorValue').value;
            var timeSlot = start + "," + end + "," + doctor;
            $.ajax({
                url: Feng.ctxPath + '/doctorLooked/getDataListByDoctor/' + timeSlot,
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    var events = [];
                    $.each(data, function (key, value) {
                        var obj = {
                            id: value.customerId,
                            title: value.appointmentPayService,
                            start: new Date(Date.parse(value.startTime)),
                            end: new Date(Date.parse(value.endTime)),
                            customerName: value.customerName,
                            resourceId: value.id,
                            arrivalStatus: value.arrivalStatus,
                            accountarrears: value.accountarrears
                        };
                        if (value.arrivalStatus == '1') {
                            obj.backgroundColor = "#4099ff";
                            obj.borderColor = "#4099ff"
                        } else if (value.arrivalStatus == '2') {
                            obj.backgroundColor = "#10428b";
                            obj.borderColor = "#10428b"
                        } else if (value.arrivalStatus == '3') {
                            obj.backgroundColor = "#ffba40";
                            obj.borderColor = "#ffba40"
                        } else if (value.arrivalStatus == '4') {
                            obj.backgroundColor = "#2dc87e";
                            obj.borderColor = "#2dc87e"
                        } else if (value.arrivalStatus == '5') {
                            obj.backgroundColor = "#61b740";
                            obj.borderColor = "#61b740"
                        } else if (value.arrivalStatus == '6') {
                            obj.backgroundColor = "#017cdc";
                            obj.borderColor = "#017cdc"
                        } else if (value.arrivalStatus == '7') {
                            obj.backgroundColor = "gray";
                            obj.borderColor = "gray"
                        }
                        events.push(obj)
                    });
                    callback(events)
                }
            })
        },
        eventRender: function (calEvent, element, view) {
            if (calEvent.customerName == "" || calEvent.customerName == null) {
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>")
            }
        },
        eventAfterRender: function (calEvent, element, view) {
            var data3 = parseInt(calEvent.end._d - calEvent.start._d) / 1000 / 60;
            if (element[0].clientWidth < 24) {
                element[0].innerHTML = ""
            } else if (element[0].clientWidth >= 24 && element[0].clientWidth < 45) {
                element[0].innerHTML = "";
                element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
            } else {
                if (calEvent.accountarrears != 0) {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    }
                } else {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div>")
                    }
                }
            }
        }
    });
    var data = new Date();
    var Year = data.getFullYear();
    var Month = data.getMonth() + 1;
    var day = data.getDate();
    var Hours = data.getHours();
    var minute = data.getMinutes();
    if (Month < 10) {
        Month = "0" + Month
    }
    if (day < 10) {
        day = "0" + day
    }
    if (Hours < 10) {
        Hours = "0" + Hours
    }
    if (minute > 0 && minute < 15) {
        $("#startTime").val(Year + "-" + Month + "-" + day + " " + Hours + ":15:00")
    } else if (minute > 15 && minute < 30) {
        $("#startTime").val(Year + "-" + Month + "-" + day + " " + Hours + ":30:00")
    } else if (minute > 30 && minute < 45) {
        $("#startTime").val(Year + "-" + Month + "-" + day + " " + Hours + ":45:00")
    } else if (minute > 45 && minute < 60) {
        $("#startTime").val(Year + "-" + Month + "-" + day + " " + Hours + ":59:00")
    }
    viewUpdate()
});

function getListInfo() {
    $.ajax({
        url: Feng.ctxPath + "/doctorLooked/getListInfo",
        data: {"projectCategory": $("#projectCategory").val()},
        type: "POST",
        success: function (data) {
            var text = '';
            for (var i = 0; i < data.length; i++) {
                text += '<div><label style="font-weight: 500;margin:0;"><input type="checkbox" name="about" style="vertical-align: middle;margin: 0 8px 0;" value="' + data[i].projectName + '" >' + data[i].projectName + '</label></div>'
            }
            $("#projectType").html(text)
        }
    })
}

function addSet() {
    var index = layer.open({
        type: 2,
        title: '预约项目设置',
        area: ['80%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/doctorLooked/add_project'
    });
    this.layerIndex = index
}

checkDate = function () {
    var value = $("#startTime").val();
    doctor = document.getElementById('doctorValue').value;
    starts = value.substring(0, 10) + " 00:00:00";
    ends = value.substring(0, 10) + " 23:59:59";
    $("#startTimeValue").val(starts);
    $("#startDocumentValue").val(starts);
    $('#calendars').fullCalendar('gotoDate', value.substring(0, 10));
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {"doctor": doctor, "value": value.substring(0, 10)},
        dataType: "json",
        success: function (data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({"pointer-events": "none", "cursor": "not-allowed"})
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({"pointer-events": "", "cursor": ""});
                viewUpdate()
            }
        }
    })
};
$("#startTime").on('input', function () {
    if ($("#startTime").val().length == 19) {
        viewUpdate()
    }
});

function refreshChange() {
    document.getElementById('doctorValue').value = $("#doctor").val();
    var doctor = document.getElementById('doctorValue').value;
    var value = $("#startDocumentValue").val().substring(0, 10);
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {"doctor": doctor, "value": value},
        dataType: "json",
        success: function (data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({"pointer-events": "none", "cursor": "not-allowed"})
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({"pointer-events": "", "cursor": ""})
            }
        }
    })
}

function submission() {
    if (eventData == "" || eventData == undefined || eventData == null) {
        alert("请选择预约时间！");
        return false
    }
    var startTimeValue = eventData.split(",")[0];
    var endTimeValue = eventData.split(",")[1];
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var check = $("input[type='checkbox']:checked");
    var treatmentUnit = $("#treatmentUnit").val();
    if (fieldTc == null || fieldTc == "") {
        alert("请选择TC！");
        return
    }
    if (doctor == null || doctor == "") {
        alert("请选择医生！");
        return
    }
    if (treatmentUnit == null || treatmentUnit == "") {
        alert("请选择科室！");
        return
    }
    var projectData = "";
    for (var i = 0; i < check.length; i++) {
        projectData += $(check[i]).val() + ","
    }
    var tiem = new Date();
    var YY = tiem.getFullYear();
    var MM = tiem.getMonth() + 1;
    var DD = tiem.getDate();
    if (MM < 10) {
        MM = "0" + MM
    }
    if (DD < 10) {
        DD = "0" + DD
    }
    var weekEnd = startTimeValue.split(" ")[0] + " 20:00:00";
    if (startTimeValue > weekEnd) {
        alert("预约时间不在医生工作时间内！");
        return
    }
    $.ajax({
        url: Feng.ctxPath + "/customer/addCustomerFzs",
        type: "post",
        data: {
            "reservationsId": reservationsId,
            "endTimeValue": endTimeValue,
            "startTimeValue": startTimeValue,
            "treatmentUnit": treatmentUnit,
            "customerPhone": customerPhone,
            "customerId": customerId,
            "projectData": projectData,
            "fieldTc": fieldTc,
            "doctor": doctor,
            "isFz": "2",
            "remarks": remarks
        },
        success: function (data) {
            if (data == 11) {
                alert('预约时间必须大于当前时间!')
            } else {
                Feng.success('预约成功!');
                window.parent.$('#calendar').fullCalendar('refetchEvents');
                parent.layer.close(parent.layer.getFrameIndex(window.name))
            }
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        }
    })
}

function submissions() {
    if (eventData == "" || eventData == undefined || eventData == null) {
        alert("请选择预约时间！");
        return false
    }
    var startTimeValue = eventData.split(",")[0];
    var endTimeValue = eventData.split(",")[1];
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var check = $("input[name='about']:checked").val();
    var treatmentUnit = $("#treatmentUnit").val();
    if (fieldTc == null || fieldTc == "") {
        alert("请选择TC！");
        return
    }
    if (doctor == null || doctor == "") {
        alert("请选择医生！");
        return
    }
    if (treatmentUnit == null || treatmentUnit == "") {
        alert("请选择科室！");
        return
    }
    var tiem = new Date();
    var YY = tiem.getFullYear();
    var MM = tiem.getMonth() + 1;
    var DD = tiem.getDate();
    if (MM < 10) {
        MM = "0" + MM
    }
    if (DD < 10) {
        DD = "0" + DD
    }
    var weekEnd = startTimeValue.split(" ")[0] + " 20:00:00";
    if (startTimeValue > weekEnd) {
        alert("预约时间不在医生工作时间内！");
        return
    }
    var projectData = "";
    for (var i = 0; i < $("input[type='checkbox']:checked").length; i++) {
        projectData += $($("input[type='checkbox']:checked")[i]).val() + ","
    }
    var startTime = $("#startTime").val();
    var isFz = $("#isFz").val();
    var date = new Date();
    var currentYear = date.getFullYear();
    var currentMonth = date.getMonth() + 1;
    var currentDay = date.getDate();
    if (currentMonth < 10) currentMonth = "0" + currentMonth;
    if (currentDay < 10) currentDay = "0" + currentDay;
    var nowTime = currentYear + "-" + currentMonth + "-" + currentDay;
    if (isFz == "1" && startTime.substring(0, 10) != nowTime) {
        alert("复诊到店，开始时间不能大于今天！");
        return
    }
    $.ajax({
        url: Feng.ctxPath + "/customer/addCustomerFzs",
        type: "post",
        data: {
            "reservationsId": reservationsId,
            "endTimeValue": endTimeValue,
            "startTimeValue": startTimeValue,
            "treatmentUnit": treatmentUnit,
            "customerPhone": customerPhone,
            "customerId": customerId,
            "projectData": projectData,
            "fieldTc": fieldTc,
            "doctor": doctor,
            "isFz": isFz,
            "remarks": remarks
        },
        success: function (data) {
            if (data == 11) {
                alert('预约时间必须大于当前时间!')
            } else {
                Feng.success('预约成功!');
                if (parent.$("#isDorj").val() == 'st') {
                    window.parent.$('#calendar').fullCalendar('refetchEvents');
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                } else if (parent.$("#isDorj").val() == 'dd') {
                    window.parent.location.reload();
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                } else if (parent.$("#isDorj").val() == 'ys') {
                    window.parent.location.reload();
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                } else if (parent.$("#isDorj").val() == 'yss') {
                    window.parent.DoctorLooked.search();
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                } else if (parent.$("#isDorj").val() == 'qt') {
                    window.parent.Customer.search();
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                } else {
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                }
            }
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        }
    })
}

function UpdateSubmission() {
    if (eventData == "" || eventData == undefined || eventData == null) {
        alert("请选择预约时间！");
        return false
    }
    var startTimeValue = eventData.split(",")[0];
    var endTimeValue = eventData.split(",")[1];
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var check = $("input[type='checkbox']:checked");
    var projectData = "";
    for (var i = 0; i < check.length; i++) {
        projectData += $(check[i]).val() + ","
    }
    $.ajax({
        url: Feng.ctxPath + "/customer/updateCustomerFzs",
        type: "post",
        data: {
            "reservationsId": reservationsId,
            "endTimeValue": endTimeValue,
            "startTimeValue": startTimeValue,
            "customerPhone": customerPhone,
            "customerId": customerId,
            "projectData": projectData,
            "fieldTc": fieldTc,
            "doctor": doctor,
            "remarks": remarks
        },
        success: function (data) {
            alert('修改成功!');
            $('#calendars').fullCalendar('refetchEvents');
            window.parent.$('#calendar').fullCalendar('refetchEvents');
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        }
    })
}